package logic

import (
	"context"
	"errors"
	"gorm.io/gorm"
	"house/models"

	"house/houserpc/houserpc"
	"house/houserpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type HouseAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewHouseAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *HouseAddLogic {
	return &HouseAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *HouseAddLogic) HouseAdd(in *houserpc.HouseAddRequest) (*houserpc.HouseAddResponse, error) {
	// todo: add your logic here and delete this line
	var class models.Class
	models.DB.Where("id=?", in.ClassId).Find(&class)
	if class.ID == 0 {
		return nil, errors.New("当前分类不存在")
	}
	house := models.House{
		Model:        gorm.Model{},
		Title:        in.Title,
		Price:        float64(in.Price),
		Context:      in.Context,
		ClassId:      int(in.ClassId),
		UserId:       int(in.UserId),
		CollectCount: int(in.CollectCount),
	}
	if in.Title == "" || in.Context == "" || in.Price == 0.0 || in.ClassId == 0 {
		return nil, errors.New("标题、分类、价格、描述为必填项")
	}
	models.DB.Create(&house)
	return &houserpc.HouseAddResponse{
		HouseId: int64(house.ID),
	}, nil
}
